package com.mapbased.wfw.ws;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.HttpException;
import java.io.IOException;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: mapbased.com</p>
 *
 * @author chy_hs(Baily)
 * @version 1.0
 */
public class ReqSender
{

    static MultiThreadedHttpConnectionManager connectionManager=new
        MultiThreadedHttpConnectionManager();
    static HttpClient client=new HttpClient(connectionManager);

  public String getOkContent(GetMethod method)
        throws RuntimeException,IOException
    {

      try
      {
          // Execute the method.
          int statusCode=client.executeMethod(method);

          if(statusCode == HttpStatus.SC_OK)
          {
              return method.getResponseBodyAsString();
          }
          throw new java.lang.RuntimeException("WS Http Error:"+statusCode);

      }


      finally
      {
          // Release the connection.
          method.releaseConnection();
      }

  }
    /**
     *Get Html Content from the url
     */

    public String getContent(GetMethod method)
    {

        try
        {
            // Execute the method.
            int statusCode=client.executeMethod(method);

            //if(statusCode == HttpStatus.SC_OK)
            {
                return method.getResponseBodyAsString();
            }

        }

        catch(Exception e)
        {
            return new StringBuffer("<b> ").append(e.getMessage()).append(
                "</b>").toString();
        }
        finally
        {
            // Release the connection.
            method.releaseConnection();
        }
    }

    // HttpClient client=new HttpClient();
    public WSResult execute(PostMethod method)
    {
        try
        {
            // Execute the method.
            int statusCode=client.executeMethod(method);

            if(statusCode == HttpStatus.SC_OK)
            {

                java.io.ObjectInputStream ois=new java.io.ObjectInputStream(
                    method.getResponseBodyAsStream());

                return(WSResult)ois.readObject();
            }
            else
            {
                return WSResult.errorResult("WS HTTP ERROR:" + statusCode);
            }
        }

        catch(Exception e)
        {
            throw new java.lang.RuntimeException(e);
        }
        finally
        {
            // Release the connection.
            method.releaseConnection();
        }

    }

// Create a method instance.


}
